package com.ybfenpan.controller.admin.shop;


import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ybfenpan.controller.core.BaseController;
import com.ybfenpan.model.shop.Goods;
import com.ybfenpan.service.shop.GoodsService;
import com.ybfenpan.utils.FileUtils;
import com.ybfenpan.utils.MapUtil;
import com.ybfenpan.utils.SysConst;
import com.ybfenpan.utils.Tools;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;






/**
 * Created by Administrator on 2016/3/25.
 */
@Controller

public class GoodsAddController extends BaseController {
    @Resource
    private GoodsService goodsService;
    

	/**
     * 异步上传图片
     * @param request
     * @return
	 * @throws IOException 
     * @throws Exception
     */
	@RequestMapping("admin/shop/imgUpload.shtml")
	@ResponseBody
	public void ajaxTuFahterAction(@RequestParam MultipartFile filedata, ModelMap model, HttpServletRequest request, HttpServletResponse response) throws IOException {
		String err="";					//错误消息（没有就不填写）	 
		String msg="";						//图片相对地址
		boolean success=false;				// 和form表单里回调函数success和failure对应，一定要有。
		String info="";	 				// 上传成功与否的提示信息;	 				// 上传成功与否的提示信息
		 
		
		System.out.println("文件上传中");
			
		System.out.println("file.getOriginalFilename():"+filedata.getOriginalFilename());
		HashMap resultformMap = new HashMap();
		if(filedata.getOriginalFilename()!=null||filedata.getOriginalFilename()!=""){
	
			String docType = "message"; //保存的文件夹名称
	    	
	    	String fileName = filedata.getOriginalFilename();
	    	String docName =  FileUtils.getUUIDFileName(fileName);
	    	//复制保存到E盘
	        String newFile = SysConst.TMP_FILE + docName;
	        
	        
	        String fileContentType=filedata.getContentType();
	        //后缀名
			String ext = fileName.substring(fileName.lastIndexOf('.')+1).toLowerCase();
		
			List<String> arrowType = Arrays.asList("images/gif","images/jpg","images/jpeg","images/pjpeg","images/png","images/bmp","image/gif","image/jpg","image/jpeg","image/pjpeg","image/png","image/bmp","image/x-png");
			List<String> arrowExt = Arrays.asList("gif","jpg","jpeg","png","bmp");
			
			 
			if(!(arrowType.contains(fileContentType.toLowerCase()) && arrowExt.contains(ext))){ 
				 err="上传文件只接收gif/jpg/jpeg/png/bmp类型,您的文件类型为！"+fileContentType;
				 success=false;
				 info = "上传失败！";
			}else{
				if(filedata.getSize()>(2*1024*1024)){ 
					err="图片大小不能大于2M!";
					success=false;
					info = "上传失败！";
				}
				/******************  业务代码      **********************/
				if(err.length()<1){
					//文件存储到硬盘
	        		boolean flag = FileUtils.createFileToDisk(newFile, filedata.getInputStream());
	        		
	        		 if(flag){
                         String tmpFile = Tools.getWebPath(this.getClass())+SysConst.TMP_FILE+docName;
                         FileUtils.copyFile(newFile,tmpFile);
                         //FileUtils.copyFile(newFileTomcat1,tmpFile);
                         //FileUtils.copyFile(newFileTomcat2,tmpFile);
                         
                         String path = request.getContextPath();
                     	String port = (0<request.getServerPort()) ? (":"+request.getServerPort()) : "";
                     	String basePath = request.getScheme()+"://"+request.getServerName()+port+path+"/";
                        
                     	msg = basePath+SysConst.TMP_FILE+docName;
                     	success = true;
        				info = "上传成功！"; 
                     }else{ 
                    		err="上传失败！！";
        					success=false;
        					info = "上传失败！";
                     }
	        		 resultformMap.put("err", err);
	        		 resultformMap.put("msg", msg);
	        		 resultformMap.put("success", success);
	        		 resultformMap.put("info", info);
	        		 renderSuccess(response, true, resultformMap);
				}
			}
		}else{
			err="获取不到图片！！";
			success=false;
			info = "上传失败！";
			resultformMap.put("err", err);
	   		 resultformMap.put("msg", msg);
	   		 resultformMap.put("success", success);
	   		 resultformMap.put("info", info);
	   		 renderSuccess(response, true, resultformMap);
		}
		
 
	}

   

    @RequestMapping("admin/shop/goodsAdd.shtml")
    public String add(@RequestParam MultipartFile file, ModelMap model,HttpServletRequest request, HttpServletResponse response) throws Exception{
    	 
    	
    	Map formMap = getParameterMap(request);
    	boolean result = true;
    	
		
		//新增
    	String title = MapUtil.getString(formMap, "title");
    	String detail = MapUtil.getString(formMap, "detail");
    	Integer totalNum = MapUtil.getIntValue(formMap, "totalNum");
    	Double price= MapUtil.getDouble(formMap, "price");
    	 
    	if (title==null||"".equals(title)) {
    		setMessage(model,"请输入名称。");
			result = false;
		}
    	
    	if(totalNum<0){
    		setMessage(model,"请输入正确的数量。");
			result = false;
    	}
    	
    	if(price==null||price<0){
    		setMessage(model,"请输入正确的价格。");
			result = false;
    	}
    	
		if(file.getOriginalFilename()==null||file.getOriginalFilename()==""){
			setMessage(model,"请上传产品图片。");
			result = false;
			
		}else{
			
			
        	
        	String fileName = file.getOriginalFilename();
        	String docName =  FileUtils.getUUIDFileName(fileName);
        	//复制保存到E盘
            String newFile = SysConst.TMP_FILE + docName;
            
            
            String fileContentType=file.getContentType();
            //后缀名
			String ext = fileName.substring(fileName.lastIndexOf('.')+1).toLowerCase();
		
			List<String> arrowType = Arrays.asList("images/gif","images/jpg","images/jpeg","images/pjpeg","images/png","images/bmp","image/gif","image/jpg","image/jpeg","image/pjpeg","image/png","image/bmp","image/x-png");
			List<String> arrowExt = Arrays.asList("gif","jpg","jpeg","png","bmp");
			
			 
			if(!(arrowType.contains(fileContentType.toLowerCase()) && arrowExt.contains(ext))){
				 
				setMessage(model,"上传文件只接收gif/jpg/jpeg/png/bmp类型,您的文件类型为！"+fileContentType);
				result = false;
			}else{
				
				if(file.getSize()>(4*1024*1024)){
					
					setMessage(model,"上传图片不能大于4M。");
					result = false;
				}
				//文件存储到硬盘
        		boolean flag = FileUtils.createFileToDisk(newFile, file.getInputStream());
				 
                if(flag){
                    String tmpFile = Tools.getWebPath(this.getClass())+SysConst.TMP_FILE+docName;
                    FileUtils.copyFile(newFile,tmpFile);
                    
                    String path = request.getContextPath();
                	String port = (0<request.getServerPort()) ? (":"+request.getServerPort()) : "";
                	String basePath = request.getScheme()+"://"+request.getServerName()+port+path+"/";
                    
                	Random random = new Random(); 
    				SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss"); 
    				String goodsNo="P"+formatter.format(new Date()) + random.nextInt(2) ;
                    
                    Goods goods = new Goods();
        			goods.setTitle(title);
        			goods.setDetail(detail);
        			goods.setTotalNum(totalNum);
        			goods.setImgName(docName);
        			goods.setImgPath(basePath+SysConst.TMP_FILE);
        			goods.setPrice(price);
        			goods.setGoodsNo(goodsNo);
                    goodsService.saveOrUpdate(goods);
                     
                    return "redirect:goodsList.shtml";
                }else{
                	 
                	setMessage(model,"上传图片失败");
                	result = false;
                }
                
			}
				
		     
		}
        	
    	
	
		if(!result){
			 
			return "admin/shop/goodsAdd";
		}
    	
    	return "redirect:goodsList.shtml";
		
     
    }
 
     
}
